// This File is part of the "nyaqt" Project
// 
// Copyright  2009 sometmes@gmail.com
// All rights reserved
// 
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Text;
using EnvDTE80;
using System.Diagnostics;
using System.IO;
using Microsoft.Win32;
using System.Windows.Forms;


namespace SmAddin
{
    internal enum InitEnum
    {
        Startup = 1,
        Shutdown = 2
    }
}

namespace SmAddin.Commands
{
    class OpenApartCommand
    {
        const string _sharedInstanceId = "SharedInstanceId_";

        DTE2 _dte;
        public DTE2 DTE
        {
            get { return _dte; }
            set { _dte = value; }
        }

        public static void CheckResetSharedInstance(EnvDTE80.DTE2 dte, InitEnum init)
        {
            int instanceid = 0;
            if (init == InitEnum.Shutdown)
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(Konstants.PluginRegKey, true))
                {
                    instanceid = (int)key.GetValue(_sharedInstanceId + dte.Version, 0);
                }
            }
            Process current = Process.GetCurrentProcess();

            if (instanceid == current.Id || ROTHelper.CountVisualStudioInstance(dte.Version) == 1)
            {
                ResetSharedInstance(dte);
            }
        }

        public static void ResetSharedInstance(EnvDTE80.DTE2 dte)
        {
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(Konstants.PluginRegKey, true))
            {
                key.SetValue(_sharedInstanceId + dte.Version, 0);
            }
        }

        public void SetSharedInstance(int processid, EnvDTE80.DTE2 dte)
        {
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(Konstants.PluginRegKey, true))
            {
                key.SetValue(_sharedInstanceId + dte.Version, processid);
            }
        }

        DTE2 GetSharedInstance(EnvDTE80.DTE2 dte)
        {
            int instanceid = 0;
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(Konstants.PluginRegKey, true))
            {
                instanceid = (int)key.GetValue(_sharedInstanceId + dte.Version, 0);
            }

            DTE2 sharedDte = null;

            if (instanceid != 0)
                sharedDte = (DTE2) ROTHelper.GetVisualStudioInstance(DTE.Version, instanceid);

            if (sharedDte == null)
            {
                string devenv = DTE.FileName;
                Process p = Process.Start(devenv);
                instanceid = p.Id;
                SetSharedInstance(instanceid, dte);
                sharedDte = (DTE2) ROTHelper.GetVisualStudioInstance(DTE.Version, instanceid);
                while (sharedDte == null)
                {
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(2000);
                    sharedDte = (DTE2) ROTHelper.GetVisualStudioInstance(DTE.Version, instanceid);
                }
            }
            if (sharedDte == null)
            {
                MessageBox.Show("Cannot connect to DevEnv");
                return null;
            }
            return sharedDte;
        }

        public void Exec()
        {
            
            string devenv = DTE.FileName;
            string vsta = Path.Combine(Path.GetDirectoryName(devenv), "vsta.exe");
            object[] selitems = DteHelper.SelectedItemsInSolutionExplorer(DTE);
            if (selitems == null || selitems.Length == 0)
                return;
            foreach (object item in selitems)
            {
                string file = DteHelper.GetHierarchyItemPath(item);
                DTE2 dte = GetSharedInstance(this.DTE);
                if (Control.ModifierKeys == Keys.Shift)
                    dte.ItemOperations.OpenFile(file, EnvDTE.Constants.vsViewKindDesigner);
                else
                    dte.ItemOperations.OpenFile(file, EnvDTE.Constants.vsViewKindCode);
                dte.MainWindow.Activate();
            }
            //string args = "";
            //foreach (object item in selitems)
            //{
            //    string file = DteHelper.GetHierarchyItemPath(item);
            //    args += " /Edit \"" + file + "\"";
            //}
            //if (!string.IsNullOrEmpty(args))
            //{
            //    if (File.Exists(vsta))
            //        Process.Start(vsta, args);
            //    else
            //        Process.Start(devenv, args);
            //}
        }
    }
}
